package com.woniuxy.controller;

import com.aliyun.oss.OSSClient;
import com.woniu.entity.utils.ResponseEntity;
import com.woniuxy.entity.UploadResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * @Author WY
 * @PackageName phase-iv-cyx
 * @Package com.woniuxy.controller
 * @Date 2022/12/19 13:24
 * @Version 1.0
 */
@RestController
@RequestMapping("/oss")
public class OssController {
    @Resource
    private OSSClient ossClient;
    //演示简化配置
    private static final String BUCKETNAME = "wy-woniu92";
    private String baseUrl = "https://wy-woniu92.oss-cn-hangzhou.aliyuncs.com/";
    @PostMapping("/update")
    public ResponseEntity update(MultipartFile file) throws IOException {
        //1.获取文件名
        String filename = file.getOriginalFilename();
        //2.获取文件流
        InputStream inputStream = file.getInputStream();
        //3.配置oss客户端，通常是通过配置类直接配置好，我们这里简略配置
        ossClient.putObject(BUCKETNAME,filename,inputStream);
        //  配置过期时间是60天
        Date date = new Date(System.currentTimeMillis() + 1000 * 3600 * 24 * 60);
        //  获取到url返回值
        URL url = ossClient.generatePresignedUrl(BUCKETNAME, filename, date);
        //4.获取返回数据
        UploadResult ossUpdateResponseEntity = new UploadResult(filename, url.toString());
        //5.封装数据并返回给前端
        return new ResponseEntity(ossUpdateResponseEntity);
    }
    @DeleteMapping("/del")
    public ResponseEntity del(String fileName){
        ossClient.deleteObject(BUCKETNAME,fileName);
        return ResponseEntity.SUCCESS;
    }
}
